<template>
    <div class="comment-head">
        <el-row>
            <el-col :span="1">
                <el-avatar :size="50" :src="circleUrl" style="margin-right: 30px;"/>
            </el-col>
            <el-col :span="23">
                <el-input v-model="config.commentContent" type="textarea" style="width: 80%;"/>
                <el-button type="success" round style="margin-top: auto; margin-left: 20px;"
                           :disabled="config.sendCommentButtonDispable" @click="clickSendComment(false)">发送
                </el-button>
                <el-row style="margin-top: 10px;">
                    <el-button round @click="config.chooseCallUserVisible = true">@</el-button>

                    <el-select v-show="config.chooseCallUserVisible" v-model="config.callUserIds" multiple filterable
                               remote
                               reserve-keyword placeholder="请输入用户昵称" :remote-method="inputUserName" :loading="loading"
                               style="margin-left: 10px;">
                        <el-option v-for="item in config.queryCallUsers" :key="item.id" :value="item.id">{{
                                item.nickName
                            }}
                        </el-option>
                    </el-select>


                    <el-button v-show="config.chooseCallUserVisible" round
                               @click="clickDoneChooseCallUser(false)">确定
                    </el-button>

                    <el-tag v-show="!config.chooseCallUserVisible" @close="removeCallUser(callUser, false)" closable
                            v-for="callUser in config.callUsers" :key="callUser.id"
                            style="margin-top:auto; margin-bottom: auto;">
                        {{ callUser.nickName }}
                    </el-tag>

                </el-row>
            </el-col>


        </el-row>

    </div>
    <div class="comment-body">
        <el-row v-if="comments.lineCount == 0">
            <el-empty description="还没有评论哦" style="margin: 0 auto ;"/>
        </el-row>
        <el-row v-if="comments.lineCount > 0">
            <el-button :type="config.orderTypeHotButtonStyle" @click="changeOreerType(true)">按热度排序</el-button>
            <el-button :type="config.orderTypeTimeButtonStyle" @click="changeOreerType(false)">按时间排序</el-button>
            <el-divider style="margin-top: 0px;"/>
        </el-row>

        <el-row v-for="(rootComment, rootCommentIndex) in comments.data" :key="rootComment.id">
            <el-col :span="1">
                <el-avatar :size="50" src="" style="margin-right: 10px; float: right;"/>
            </el-col>
            <el-col :span="23">
                <el-row style="margin: 0px; margin-bottom: 5px;">
                    <el-text class="mx-1">{{ rootComment.user.nickName }}</el-text>
                    <el-text class="mx-1" style="margin-left: 10px;">{{ rootComment.user.level + "级" }}</el-text>
                </el-row>
                <el-row style="max-width: 80%;">
                    <span style="max-width: 80%; word-break: break-all;"> {{ rootComment.content }}</span>
                </el-row>
                <el-row style="margin-top: 5px;">
                    <el-text class="mx-1" type="info" size="small">{{ rootComment.sendDateTime }}</el-text>
                    <i class="iconfont icon-like-full icon-not-active"
                       v-if="!rootComment.currentUserLike"
                       @click="likeComment(true, rootComment.id, rootCommentIndex)"/>

                    <i class="iconfont icon-like-full icon-like-active"
                       v-else
                       @click="cancelLikeComment(true, rootComment.id, rootCommentIndex)"/>

                    <el-text class="mx-1" type="info" style="margin-left: 5px">{{ rootComment.likeNumber }}</el-text>

                    <i class="iconfont icon-badreview-full icon-not-active"
                       v-if="!rootComment.currentUserNotLike"
                       @click="notLikeComment(true, rootComment.id, rootCommentIndex)"/>
                    <i class="iconfont icon-badreview-full icon-not-like-active"
                       v-else
                       @click="cancelNotLikeComment(true, rootComment.id, rootCommentIndex)"/>

                    <el-link type="info" style="margin-left: 20px;"
                             @click="clickReplyComment(rootComment.id, rootComment.id)">回复
                    </el-link>
                    <el-link type="danger" style="margin-left: 10px;" v-if="rootComment.commentSenderIsMe"
                             @click="deleteComment(rootComment.id, true)">删除
                    </el-link>
                </el-row>
                <!-- ============== -->
                <el-row style="margin-top: 20px;" v-for="(sonComment, sonCommentIndex) in rootComment.sonComments">

                    <el-col :span="1">
                        <el-avatar :size="50" :src="circleUrl" style="margin-right: 10px; float: right;"/>
                    </el-col>
                    <el-col :span="23">
                        <el-row style="margin: 0px; margin-bottom: 5px;">
                            <el-text class="mx-1">{{ sonComment.user.nickName }}</el-text>
                            <el-text class="mx-1" style="margin-left: 10px;">{{ sonComment.user.level + "级" }}</el-text>
                        </el-row>
                        <el-row>
                            回复<span style="color:#409eff" v-if="sonComment.replyCommentUserNickName != null">{{
                                sonComment.replyCommentUserNickName
                            }}:</span>
                            <span v-else style="color: red;">已删除的评论:</span>
                            <span style="max-width: 80%; word-break: break-all;">{{ sonComment.content }}</span>
                        </el-row>
                        <el-row style="margin-top: 5px;">
                            <el-text class="mx-1" type="info" size="small">{{ sonComment.sendDateTime }}</el-text>


                            <i class="iconfont icon-like-full icon-not-active"
                               v-if="!sonComment.currentUserLike"
                               @click="likeComment(false, sonComment.id, rootCommentIndex, sonCommentIndex)"/>

                            <i class="iconfont icon-like-full icon-like-active"
                               v-else
                               @click="cancelLikeComment(false, sonComment.id, rootCommentIndex, sonCommentIndex)"/>

                            <el-text class="mx-1" type="info" style="margin-left: 5px">{{
                                    sonComment.likeNumber
                                }}
                            </el-text>

                            <i class="iconfont icon-badreview-full icon-not-active"
                               v-if="!sonComment.currentUserNotLike"
                               @click="notLikeComment(false, sonComment.id, rootCommentIndex, sonCommentIndex)"/>
                            <i class="iconfont icon-badreview-full icon-not-like-active"
                               v-else
                               @click="cancelNotLikeComment(false, sonComment.id, rootCommentIndex, sonCommentIndex)"/>

                            <el-link type="info" style="margin-left: 20px;"
                                     @click="clickReplyComment(rootComment.id, sonComment.id)">回复
                            </el-link>

                            <el-link type="danger" style="margin-left: 10px;" v-if="sonComment.commentSenderIsMe"
                                     @click="deleteComment(sonComment.id, false)">删除
                            </el-link>

                        </el-row>
                        <el-row>

                        </el-row>

                    </el-col>

                </el-row>
                <el-row v-if="rootComment.sonCommentTotal > 4">
                    <div class="example-pagination-block">
                        <el-pagination layout="prev, pager, next" small
                                       @current-change="changeSonCommentPageNumber(rootComment.id, rootCommentIndex)"
                                       :page-size="4"
                                       :pager-count="5" :total="rootComment.sonCommentTotal"
                                       v-model:current-page="rootComment.currentPage"/>
                    </div>
                </el-row>
                <!-- ============== -->
                <el-divider style="margin-top: 10px; margin-bottom: 10px;"/>
            </el-col>
        </el-row>
        <!-- 跟级评论的分页器 -->
        <div class="example-pagination-block" v-if="comments.lineCount > 0">
            <el-pagination layout="prev, pager, next" :size="comments.pageSize" :total="comments.lineCount"
                           v-model:current-page="comments.currentPageNumber" @current-change="changeCommentPageNumber"/>
        </div>
    </div>
    <!-- 回复评论 -->
    <el-drawer v-model="config.replyDrawerVisible" direction="btt" title="I am the title" :with-header="false">
        <div style="margin-left: 20%;">
            <el-row>
                回复小米粒:
            </el-row>
            <el-row>
                <el-input v-model="reply.commentContent" type="textarea" style="width: 80%;"/>
                <el-button type="success" round style="margin-top: auto; margin-left: 20px;"
                           :disabled="config.sendCommentButtonDispable" @click="clickSendComment(true)">回复
                </el-button>
            </el-row>
            <el-row>
                <el-row style="margin-top: 10px;">
                    <el-button round @click="reply.chooseCallUserVisible = true">@</el-button>
                    <el-select v-show="reply.chooseCallUserVisible" v-model="reply.callUserIds" multiple filterable
                               remote
                               reserve-keyword placeholder="请输入用户昵称" :remote-method="replyInputUserName"
                               :loading="loading"
                               style="margin-left: 10px;">
                        <el-option v-for="item in reply.queryCallUsers" :key="item.id" :value="item.id">{{
                                item.nickName
                            }}
                        </el-option>
                    </el-select>

                    <el-button v-show="reply.chooseCallUserVisible" round
                               @click="clickDoneChooseCallUser(true)">确定
                    </el-button>

                    <el-tag v-show="!reply.chooseCallUserVisible" @close="removeCallUser(callUser, true)" closable
                            v-for="callUser in reply.callUsers" :key="callUser.id"
                            style="margin-top:auto; margin-bottom: auto;">
                        {{ callUser.nickName }}
                    </el-tag>

                </el-row>
            </el-row>
        </div>
    </el-drawer>
</template>

<script>
import {useRouter} from 'vue-router'
import {reactive, onMounted, watch, computed} from 'vue'
import {ElMessageBox} from 'element-plus'

import StringUtil from '../../utils/StringUtil.js'
import InfoUtil from '../../utils/InfoUtil.js'
import RequestUtil from '../../utils/RequestUtil.js'
import UserUtil from '../../utils/UserUtil.js'

export default {
    props: ['articleId', "currentUserAvatarPath"],

    setup(props) {


        const config = reactive({
            //用户当前的评论
            commentContent: "",
            //@的用户
            callUserIds: [],
            callUsers: [],
            //发送评论按钮是否禁用
            sendCommentButtonDispable: false,
            //选择@用户的选择框是否显示
            chooseCallUserVisible: false,
            //@查询出来的用户集合
            queryCallUsers: [],
            //回复框是否展示
            replyDrawerVisible: false,
            //回复评论的id
            replyCommentId: 0,
            //父级评论id
            parentCommentId: 0,
            //根据时间或热度排序 热度true  时间false
            orderType: true,
            orderTypeHotButtonStyle: "primary",
            orderTypeTimeButtonStyle: "default",
        })
        const reply = reactive({
            commentContent: "",
            //@的用户
            callUserIds: [],
            callUsers: [],
            //选择@用户的选择框是否显示
            chooseCallUserVisible: false,
            //@查询出来的用户集合
            queryCallUsers: []
        })

        const comments = reactive({
            data: [],
            lineCount: 0,
            pageSize: 0,
            currentPageNumber: 0
        })


        const articleId = props.articleId;
        //加载评论
        const loadComment = (pageNumber) => {
            const requestData = {
                pageNumber,
                articleId,
                "orderType": config.orderType
            }
            RequestUtil.sendGetRequest("/comment/queryComment", requestData).then(
                (res) => {
                    if (res.code == 666) {
                        return
                    }
                    if (res.code != 200) {
                        InfoUtil.warning(res.message);
                        return;
                    }
                    for (let i = 0; i < res.data.length; i++) {
                        let comment = res.data[i];
                        comment.user.level = UserUtil.getUserLevel(comment.user.exp)
                        //子级评论分页
                        comment.currentPage = 1;
                        let sonComments = comment.sonComments
                        if (sonComments == null) {
                            continue;
                        }
                        for (let j = 0; j < sonComments.length; j++) {
                            let sonComment = sonComments[j];
                            sonComment.user.level = UserUtil.getUserLevel(sonComment.user.exp)
                        }
                    }
                    comments.data = res.data;
                    comments.currentPageNumber = res.currentPageNumber
                    comments.lineCount = res.lineCount
                    comments.pageSize = res.pageSize
                },
                (err) => {
                    InfoUtil.error("获取评论请求发送失败");
                }
            )
        }


        onMounted(() => {
            loadComment(1)
        })

        const likeComment = (isRootComment, commentId, rootCommentIndex, sonCommentIndex) => {
            RequestUtil.sendGetRequest("/userCommentOperation/like", {commentId}).then(
                (res) => {
                    if (res.code != 200) {
                        InfoUtil.warning(res.message)
                        return;
                    }

                    InfoUtil.success(res.message)
                    let comment = comments.data[rootCommentIndex];
                    if (!isRootComment) {
                        comment = comment.sonComments[sonCommentIndex]
                    }
                    comment.currentUserLike = true
                    comment.currentUserNotLike = false;
                    comment.likeNumber++;
                },
                (err) => {
                    InfoUtil.error('发送请求失败')
                }
            )
        }
        const cancelLikeComment = (isRootComment, commentId, rootCommentIndex, sonCommentIndex) => {
            RequestUtil.sendGetRequest("/userCommentOperation/cancelLike", {commentId}).then(
                (res) => {
                    if (res.code != 200) {
                        InfoUtil.warning(res.message)
                        return;
                    }
                    InfoUtil.success(res.message)
                    let comment = comments.data[rootCommentIndex];
                    if (!isRootComment) {
                        comment = comment.sonComments[sonCommentIndex]
                    }
                    comment.likeNumber--;
                    comment.currentUserLike = false
                    comment.currentUserNotLike = false;

                },
                (err) => {
                    InfoUtil.error('发送请求失败')
                }
            )
        }

        const notLikeComment = (isRootComment, commentId, rootCommentIndex, sonCommentIndex) => {
            RequestUtil.sendGetRequest("/userCommentOperation/notLike", {commentId}).then(
                (res) => {
                    if (res.code != 200) {
                        InfoUtil.warning(res.message)
                        return;
                    }
                    InfoUtil.success(res.message)
                    let comment = comments.data[rootCommentIndex];
                    if (!isRootComment) {
                        comment = comment.sonComments[sonCommentIndex]
                    }
                    comment.currentUserNotLike = true;
                    if (comment.currentUserLike) {
                        comment.likeNumber--;
                    }
                    comment.currentUserLike = false
                },
                (err) => {
                    InfoUtil.error('发送请求失败')
                }
            )
        }

        const cancelNotLikeComment = (isRootComment, commentId, rootCommentIndex, sonCommentIndex) => {
            RequestUtil.sendGetRequest("/userCommentOperation/cancelNotLike", {commentId}).then(
                (res) => {
                    if (res.code != 200) {
                        InfoUtil.warning(res.message)
                        return;
                    }
                    InfoUtil.success(res.message)
                    let comment = comments.data[rootCommentIndex];
                    if (!isRootComment) {
                        comment = comment.sonComments[sonCommentIndex]
                    }
                    comment.currentUserNotLike = false;
                    comment.currentUserLike = false

                },
                (err) => {
                    InfoUtil.error('发送请求失败')
                }
            )
        }


        const clickSendComment = (isReply) => {
            let content;
            if (isReply) {
                content = reply.commentContent;
            } else {
                content = config.commentContent;
            }
            if (StringUtil.isEmpty(content)) {
                InfoUtil.warning("评论不能为空");
                return
            }
            if (content.length > 1000) {
                InfoUtil.warning("评论文字太长啦!,最长一千个文字");
            }

            config.sendCommentButtonDispable = true;
            const requestData = {
                comment: {
                    articleId: articleId,
                    deleted: 1

                }
            }
            //如果是回复别人
            if (isReply) {
                requestData.comment.content = reply.commentContent
                requestData.comment.parentCommentId = config.replyCommentId
                requestData.callUserIds = reply.callUserIds
                requestData.comment.replyCommentId = config.replyCommentId;
                requestData.comment.parentCommentId = config.parentCommentId;
            } else {
                requestData.comment.content = config.commentContent
                requestData.callUserIds = config.callUserIds
            }
            RequestUtil.sendPostRequest("/comment/send", requestData).then(
                (res) => {
                    config.sendCommentButtonDispable = false;

                    if (res.code != 200) {
                        InfoUtil.warning(res.message);
                        return;
                    }
                    //如果是回复别人,则关闭掉回复框
                    if (isReply) {
                        config.replyDrawerVisible = false;
                    }
                    InfoUtil.success(res.message);
                    config.commentContent = "";
                    reply.commentContent = "";
                    config.callUserIds = []
                    config.callUsers = []
                    reply.callUserIds = []
                    reply.callUsers = []
                    loadComment(1);
                },
                (err) => {
                    config.sendCommentButtonDispable = false;
                    InfoUtil.error("发送请求失败");
                }
            )
        }

        const replyInputUserName = (nickName) => {
            fuzzyQueryUserNickName(nickName, true);
        }

        const inputUserName = (nickName) => {
            fuzzyQueryUserNickName(nickName, false);
        }

        const fuzzyQueryUserNickName = (nickName, isReply) => {
            if (StringUtil.isEmpty(nickName)) {
                return
            }
            RequestUtil.sendGetRequest("/user/fuzzyQueryByUserNickName", {"nickName": nickName}).then(
                (res) => {
                    if (res.code == 666) {
                        //忽略没有数据的情况
                        return
                    }
                    if (res.code != 200) {
                        InfoUtil.warning(res.message)
                        return;
                    }
                    if (isReply) {
                        reply.queryCallUsers = res.data;
                    } else {
                        config.queryCallUsers = res.data
                    }

                },
                (err) => {
                    InfoUtil.error("发送请求失败");
                }
            )
        }

        const clickDoneChooseCallUser = (isReply) => {
            if (isReply) {
                reply.chooseCallUserVisible = false;
                for (let i = 0; i < reply.callUserIds.length; i++) {
                    for (let k = 0; k < reply.queryCallUsers.length; k++) {
                        if (reply.callUserIds[i] == reply.queryCallUsers[k].id) {
                            let exist = false;
                            for (let j = 0; j < reply.callUsers.length; j++) {
                                if (reply.callUsers[j].id == reply.queryCallUsers[k].id) {
                                    exist = true;
                                    reply
                                    break;
                                }
                            }
                            if (!exist) {
                                reply.callUsers.push(reply.queryCallUsers[k])
                            }
                        }
                    }
                }
            } else {
                config.chooseCallUserVisible = false;
                for (let i = 0; i < config.callUserIds.length; i++) {
                    for (let k = 0; k < config.queryCallUsers.length; k++) {
                        if (config.callUserIds[i] == config.queryCallUsers[k].id) {
                            let exist = false;
                            for (let j = 0; j < config.callUsers.length; j++) {
                                if (config.callUsers[j].id == config.queryCallUsers[k].id) {
                                    exist = true;
                                    break;
                                }
                            }
                            if (!exist) {
                                config.callUsers.push(config.queryCallUsers[k])
                            }
                        }
                    }
                }
            }
        }

        const removeCallUser = (callUser, isReply) => {
            if (isReply) {
                for (let i = 0; i < reply.callUsers.length; i++) {
                    if (callUser.id == reply.callUsers[i].id) {
                        let index = reply.callUserIds.indexOf(callUser.id)
                        reply.callUserIds.splice(index, 1)
                        reply.callUsers.splice(i, 1);
                    }
                }
            } else {
                for (let i = 0; i < config.callUsers.length; i++) {
                    if (callUser.id == config.callUsers[i].id) {
                        let index = config.callUserIds.indexOf(callUser.id)
                        config.callUserIds.splice(index, 1)
                        config.callUsers.splice(i, 1);
                    }
                }
            }


        }
        //子级评论翻页
        const changeSonCommentPageNumber = (parentCommentId, rootCommentIndex) => {
            const requestData = {
                parentCommentId,
                "pageNumber": comments.data[rootCommentIndex].currentPage
            }

            RequestUtil.sendGetRequest("/comment/querySonComment", requestData).then(
                (res) => {
                    if (res.code != 200) {
                        InfoUtil.warning(res.message)
                        return;
                    }
                    for (let i = 0; i < res.data.length; i++) {
                        res.data[i].user.level = UserUtil.getUserLevel(res.data[i].user.exp);
                    }
                    comments.data[rootCommentIndex].sonComments = res.data

                },
                (err) => {

                    InfoUtil.error("发送请求失败");
                }
            )
        }

        //跟级评论翻页
        const changeCommentPageNumber = () => {
            loadComment(comments.currentPageNumber)
        }
        //删除评论
        const deleteComment = (commentId, isRootComment) => {
            let title = "确认要删除该评论吗?"
            if (isRootComment) {
                title = "确认要删除该评论吗? 该评论下所有子级评论也会被删除"
            }
            ElMessageBox.confirm(
                title,
                '提示',
                {
                    confirmButtonText: '删除',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            ).then(() => {
                RequestUtil.sendGetRequest("/comment/delete", {commentId}).then(
                    (res) => {
                        if (res.code != 200) {
                            InfoUtil.warning(res.message);
                            return
                        }
                        loadComment(1)
                        InfoUtil.success(res.message);
                    },
                    (err) => {
                        InfoUtil.error("发送删除评论请求失败");
                    }
                )

            }).catch(() => {

            });
        }

        const clickReplyComment = (parentCommentId, replyCommentId) => {
            config.replyDrawerVisible = true;
            config.parentCommentId = parentCommentId;
            config.replyCommentId = replyCommentId;
        }
        //改变排序规则
        const changeOreerType = (orderType) => {
            if (orderType == config.orderType) {
                return;
            }
            config.orderType = orderType;
            //根据热度
            if (orderType) {
                config.orderTypeHotButtonStyle = "primary"
                config.orderTypeTimeButtonStyle = "default"
            } else {
                config.orderTypeHotButtonStyle = "default"
                config.orderTypeTimeButtonStyle = "primary"
            }
            //加载评论
            loadComment(1);
        }

        return {
            config, comments, reply,
            clickSendComment, inputUserName, replyInputUserName, clickDoneChooseCallUser, removeCallUser,
            changeSonCommentPageNumber, changeCommentPageNumber, deleteComment, clickReplyComment,
            likeComment, cancelLikeComment, notLikeComment, cancelNotLikeComment, changeOreerType
        }
    }
}
</script>
<style scoped>
.comment-head {
    width: 80%;
    margin: 0 auto;
    margin-top: 50px;

}

.comment-body {
    width: 80%;
    margin: 0 auto;
    margin-top: 50px;
}

.icon-not-active {
    margin-top: auto;
    margin-bottom: auto;
    margin-left: 20px;
    font-size: larger;
    color: #8a8a8a;
}

.icon-like-active {
    margin-top: auto;
    margin-bottom: auto;
    margin-left: 20px;
    font-size: larger;
    color: #2377FFFF;
}

.icon-not-like-active {
    margin-top: auto;
    margin-bottom: auto;
    margin-left: 20px;
    font-size: larger;
    color: #ff2b2b;
}
</style>

